<?php
/*
模型基类
获得sql $bulider->toSql();
获得绑定数据 $bulider->getBindings();
 */
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class Base extends Model
{
    
    const IS_DELETE  = 1;   //删除状态

    const NO_DELETE  = 0;   //未删除状态


    public static $isdelete = 0;

    //protected $dateFormat = 'U';

    /**
     * 开启laravel默认的时间记录
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * 定义主键字段
     *
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * [批量赋值]
     * @param [type]  $params  [description]
     * @param boolean $ischeck [是否检测表字段]
     */
    public function setAttributes($params, $ischeck=false) {


        //判断数据类型
        if (is_array($params) == false || empty($params) == true) {
            return ;
        }
        //检测白名单和黑名单
        $attributes = $this->checkAttributes($params);

        //是否检测字段
        if ($ischeck == true) {

            //获得表字段
            $columns = $this->getTableColumns();

            foreach ($attributes as $key => $value) {
                //!in_array($key, $columns) && unset($attributes[$key]);
                if (!in_array($key, $columns)) unset($attributes[$key]);
            }
        }

        //循环赋值
        foreach ($attributes as $key => $value) {
            $this->$key = $value;
        }
    }

     /**
     * 全局作用域
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('isdelete', function(Builder $builder) {
            $builder->where('isdelete', '=', self::$isdelete);
        });
    }

    /**
     * 检查白名单/黑名单
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    protected function checkAttributes($params) {

        $attributes  = [];
        //当有黑名单时候 过滤黑名单
        if (empty($this->guarded) == false) { 
            foreach ($params as $key => $value) {
                !in_array($key, $this->guarded) && $attributes[$key] = $value;
            }
        }
        //当有白名单时候 过滤白名单
        if (in_array('*', $this->fillable) == false ) {
            foreach ($params as $key => $value) {
                in_array($key, $this->fillable) && $attributes[$key] = $value;
            }
        }

        return $attributes;
    }


    /**
     * 获得表结构
     * @return [type] [description]
     */
    public function getTableColumns() {

     return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
    }


}
